import React from "react";
import axios from "axios";
import { useEffect } from "react";
import { useState } from "react";
import "./Duanzilist.css";

export default function Duanzilist() {
  let [text, settext] = useState([]);
  let [show, setshow] = useState(false);
  let [cont, setcont] = useState({});
  useEffect(() => {
    async function main() {
      let res = await axios.get("http://api.xiaohigh.com/duanzi");
      let result = res.data.splice(0, 20);
      settext(result);
    }

    main();
  }, []);

  let showCont = (item) => {
    return () => {
      setshow(true);
      setcont(item);
    };
  };
  let hide = () => {
    setshow(false);
  };
  return (
    <>
      <ul className="duanzilist">
        {text.map((item, index) => {
          return (
            <li key={index} onClick={showCont(item)}>
              <h5>
                {item.name.length >= 5
                  ? item.name.substr(0, 5) + "..."
                  : item.name}
              </h5>
              <p>
                {item.text.length >= 50
                  ? item.text.substr(0, 50) + "..."
                  : item.text}
              </p>
            </li>
          );
        })}
      </ul>

      {show ? (
        <div className="bg" onClick={hide}>
          <div
            className="content animate__animated animate__backInUp"
            style={show ? { display: "block" } : { display: "none" }}
          >
            <span>X</span>
            <h3>{cont.name}</h3>
            <p>{cont.text}</p>
          </div>
        </div>
      ) : (
        ""
      )}
    </>
  );
}
